//index.js
//获取应用实例
const app = getApp()
const audio = wx.getBackgroundAudioManager()
Page({
  data: {
    musics: [],
    // 记录点击后的ID
    prevId: '',
    isPlay: false

  },
  time: function (x) {
    if (x / 1000 / 60 < 10) {
      var min = ('0' + Math.floor(x / 1000 / 60))
    } else {
      min = Math.floor(x / 1000 / 60)
    }

    if (x / 1000 % 60 < 10) {
      var sec = '0' + Math.round(x / 1000 % 60)
    } else {
      sec = Math.round(x / 1000 % 60)
    }
    return min + ':' + sec;
  },
  handleSubmit(event) {
    var keyword = event.detail.value.keyword;
    wx.showLoading({
      title:"数据正在加载中"
    })
    wx.request({
      url: `http://192.168.14.49:3000/search?keywords=${keyword}`,
      header: {
        'Content-Type': 'application/json'
      },
      method: 'get',
      dataType: 'json',
      responseType: 'text',
      success: (res) => {
        console.log(res)
        var songs = res.data.result.songs;
        var musics = [];
        songs.forEach(item => {
          var obj = {};
          obj.name = item.name;
          obj.id = item.id;
          obj.artistName = item.artists[0].name;
          obj.time = this.time(item.duration);
          obj.musicUrl = `https://music.163.com/song/media/outer/url?id=${item.id}`
          musics.push(obj)
        })
        this.setData({
          musics
        })
      wx.hideLoading();
      },
    })
  },
  handlePlay(event) {
    var { index } = event.currentTarget.dataset;
    var { id, name, musicUrl } = this.data.musics[index];
    if (id != this.data.prevId) {
      audio.title = name;
      audio.src = musicUrl;
      this.setData({
        isPlay: true,
        prevId: id
      })
    } else {
      if (this.data.isPlay) {
        audio.pause();
        this.setData({
          isPlay: false
        })
      } else {
        audio.title = name;
        audio.src = musicUrl;
        this.setData({
          isPlay: true
        })
      }
    }
  }
})